package cn.tnar.yunpark.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpToolService {

	/**编码方式*/
	private static final String DEFAULT_ENCODING = HTTP.UTF_8;
	
	/**连接超时时间*/
	private static final int TIME_OUT = 90000;
	/**读取内容连接超时时间*/
	private static final int CONNECTIONTIMEOUT = 60000;
	/**缓冲区大小*/
	private static final int BUFFER_SIZE = 1024 * 8;
	/**消息返回码(0为执行成功)*/
	public static final String MESSAGE_CODE = "/ANSWERS/0/ANS_MSG_HDR/MSG_CODE";
	/**消息返回文本*/
	public static final String MESSAGE_TEXT = "/ANSWERS/0/ANS_MSG_HDR/MSG_TEXT";
	/**回话ID*/
	public static final String MESSAGE_SESSION_ID = "/ANSWERS/0/ANS_MSG_HDR/SESSION_ID";
	/**获取返回数据*/
	public static final String GET_DATA = "/ANSWERS/0/ANS_COMM_DATA";
	
    /**
     * 客户端访问后台服务器
     * @return 结果字符串(json)
     * @throws IOException 文件异常
     * @throws ClientProtocolException 客户端异常
     */
    public static String executePostByClient(String url , String json){
    	String retult = "" ;
		HttpClient httpClient = getHttpClient();
		HttpPost post = new HttpPost(url);
		try {
	    	StringEntity entity = new StringEntity(json,"UTF-8");
			post.setHeader("Connection", "close");
			post.setHeader("Cookie", "SESSIONID=1123123123");
			post.setEntity(entity);
			HttpResponse response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				post.abort();
				return null;
			}
			retult= new String(EntityUtils.toByteArray(response.getEntity()),DEFAULT_ENCODING);
    	} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return retult;
    }

    /**
   	 * 获取HttpClient
   	 * @return HttpClient
   	 */
   	public static HttpClient getHttpClient() {
   		// Http连接参数
   		HttpParams httpParams = new BasicHttpParams();
   		// 设置连接超时时间
   		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTIONTIMEOUT);
   		// 设置连接超时时间
   		HttpConnectionParams.setSoTimeout(httpParams, TIME_OUT);
   		// 设置连接超时时间
   		HttpConnectionParams.setSocketBufferSize(httpParams, BUFFER_SIZE);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
   		
   		httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");  
   		HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
   		return httpClient;
   	}


	/**
	 * 封装请求格式
	 * @param params 参数集合
	 * @param serviceId 服务ID
	 * @return 请求参数
	 */
	public static String onRequestFormat(Map<String, String> params,String serviceId){
		/*公共参数*/
		//系统号(固定送8)
		//params.add(new ICEParameterModel("g_sysid", "8"));
		params.put("g_sysid", "8");
		//菜单编号(固定送0)
		//params.add(new ICEParameterModel("g_menuid", "0"));
		params.put("g_menuid", "0");
		//服务ID
		//params.add(new ICEParameterModel("g_funcid", serviceId));
		params.put("g_funcid", serviceId);
		//原节点编号(如果是操作员，送操作员的原节点编号)
		//params.add(new ICEParameterModel("g_srcnodeid","0"));
		params.put("g_srcnodeid","0");
		//目节点编号(如果是操作员，送操作员的需要操作客户的节点编号)
		//params.add(new ICEParameterModel("g_dstnodeid","0"));
		params.put("g_dstnodeid","0");

		params.put("g_custid", "0");
		params.put("g_custsession","0");

		//客户密码(对于非登录业务：使用用户编号作为密钥加密的密文；对于登录业务：使用用户代码登录时，以用户代码作为密钥加密；使用用户编号登录时，以用户编号作为密钥加密)
		//params.add(new ICEParameterModel("g_custpwd","0"));
		params.put("g_custpwd","1");
		//操作方式(必须送，不可以为空，后台系统送：9)
		//params.add(new ICEParameterModel("g_userway","9"));
		params.put("g_userway","9");
		//操作站点(填写格式：CPU[CPU序列号]IDE[硬盘序列号]IP[IP地址]MAC[MAC地址])
		//params.add(new ICEParameterModel("g_stationaddr","0"));
		params.put("g_stationaddr","0");

		//1-微信2-支付宝
		// params.put("g_thirdtype", "4");
		// params.put("g_thirdid", g_thirdid);
		//ICELog.i(TAG, "连接地址:" + URL_PATH);
		//ICELog.i(TAG, "接口编码:" + serviceId);
		StringBuilder sb = new StringBuilder(
				"{\"REQUESTS\":[{\"REQ_COMM_DATA\":{");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			//System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue());
			sb.append("\"" + entry.getKey() + "\"");//参数名称
			sb.append(":");
			sb.append("\"" + entry.getValue() + "\"");//参数值
			sb.append(",");
		}
		sb=new StringBuilder(sb.substring(0, sb.length()-1));
		sb.append("},\"REQ_MSG_HDR\":{\"SERVICE_ID\":\"")
				.append(serviceId).append("\"}}]}");
		return sb.toString();
	}


}
